package org.example.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

@WebServlet("/request/form-data")
@MultipartConfig
public class RequestFormData extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //form-data上传的简单类型数据，还是通过getParameter获取
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //上传的文件，就需要通过getPart获取。返回值part对象就可以获取文件信息，也可以操作
        Part head = req.getPart("head");

        //后端控制台打印日志信息
        System.out.printf("username=%s, password=%s\n", username, password);
        System.out.println("head上传文件的名称："+head.getSubmittedFileName());
        String path = "E:/TMP/"+head.getSubmittedFileName();
        head.write(path);
        System.out.println("保存在服务端本地："+path);
    }
}
